import React, { useState, useEffect } from 'react';
import { Card, Typography, List, Space, Button, Divider, Steps, Empty, Tag, Collapse, Spin } from 'antd';
import { 
  CarOutlined, 
  CompassOutlined, 
  ClockCircleOutlined, 
  EnvironmentOutlined, 
  ArrowLeftOutlined
} from '@ant-design/icons';
import { RoutePlan } from '../types';
import { useNavigate } from 'react-router-dom';
import MapComponent from '../components/MapComponent';
import { WalkIcon } from '../components/common';

const { Title, Text } = Typography;
const { Step } = Steps;
const { Panel } = Collapse;

const RouteDetail: React.FC = () => {
  const [routePlan, setRoutePlan] = useState<RoutePlan | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [mapCenter, setMapCenter] = useState<[number, number]>([121.473667, 31.230525]); // 默认上海中心
  const [mapMarkers, setMapMarkers] = useState<any[]>([]);
  const [mapPolylines, setMapPolylines] = useState<any[]>([]);
  const navigate = useNavigate();

  // 初始化加载
  useEffect(() => {
    loadRoutePlan();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 加载路线计划
  const loadRoutePlan = () => {
    setLoading(true);
    try {
      // 从会话存储中获取路线计划
      const planData = sessionStorage.getItem('selectedRoutePlan');
      if (planData) {
        const plan = JSON.parse(planData);
        setRoutePlan(plan);
        // 在地图上显示路线
        handleShowRouteOnMap(plan);
      }
    } catch (error) {
      console.error('加载路线计划失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 在地图上显示路线
  const handleShowRouteOnMap = (route: RoutePlan) => {
    // 设置地图中心为起点位置
    setMapCenter([
      route.startLocation.longitude,
      route.startLocation.latitude
    ]);
    
    // 创建标记点
    const markers = [
      // 起点标记
      {
        position: [route.startLocation.longitude, route.startLocation.latitude] as [number, number],
        title: '起点',
        label: '起点',
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
      },
      // 客户标记
      ...route.points.map((point, index) => ({
        position: [
          point.customer.location?.longitude || 0, 
          point.customer.location?.latitude || 0
        ] as [number, number],
        title: point.customer.name,
        label: `${index + 1}. ${point.customer.name}`,
        extData: point
      }))
    ];
    
    // 创建路线
    const polylines = [];
    let previousPoint = [route.startLocation.longitude, route.startLocation.latitude];
    
    // 遍历所有客户点，创建连接线
    for (let i = 0; i < route.points.length; i++) {
      const point = route.points[i];
      const customerLocation = [
        point.customer.location?.longitude || 0,
        point.customer.location?.latitude || 0
      ];
      
      // 如果有详细路线，使用详细路线点
      if (point.routeDetails && point.routeDetails.route) {
        let path = [];
        
        // 根据不同交通方式提取路径点
        if (point.travelMethod === 'driving' && point.routeDetails.route.paths && point.routeDetails.route.paths.length > 0) {
          // 驾车路线
          const steps = point.routeDetails.route.paths[0].steps;
          path = steps.flatMap((step: any) => {
            const polylinePoints = step.polyline.split(';');
            return polylinePoints.map((pointStr: string) => {
              const [lng, lat] = pointStr.split(',');
              return [parseFloat(lng), parseFloat(lat)];
            });
          });
        } else if (point.travelMethod === 'walking' && point.routeDetails.route.paths && point.routeDetails.route.paths.length > 0) {
          // 步行路线
          const steps = point.routeDetails.route.paths[0].steps;
          path = steps.flatMap((step: any) => {
            const polylinePoints = step.polyline.split(';');
            return polylinePoints.map((pointStr: string) => {
              const [lng, lat] = pointStr.split(',');
              return [parseFloat(lng), parseFloat(lat)];
            });
          });
        } else if (point.routeDetails.route.transits && point.routeDetails.route.transits.length > 0) {
          // 公交路线
          const segments = point.routeDetails.route.transits[0].segments;
          path = segments.flatMap((segment: any) => {
            if (segment.walking && segment.walking.steps) {
              return segment.walking.steps.flatMap((step: any) => {
                const polylinePoints = step.polyline.split(';');
                return polylinePoints.map((pointStr: string) => {
                  const [lng, lat] = pointStr.split(',');
                  return [parseFloat(lng), parseFloat(lat)];
                });
              });
            } else if (segment.bus && segment.bus.buslines && segment.bus.buslines.length > 0) {
              const polylinePoints = segment.bus.buslines[0].polyline.split(';');
              return polylinePoints.map((pointStr: string) => {
                const [lng, lat] = pointStr.split(',');
                return [parseFloat(lng), parseFloat(lat)];
              });
            }
            return [];
          });
        }
        
        if (path.length > 0) {
          polylines.push({
            path,
            strokeColor: getRouteColor(i),
            strokeWeight: 6,
            extData: point
          });
        } else {
          // 如果未能提取路径，则使用直线
          polylines.push({
            path: [previousPoint, customerLocation],
            strokeColor: getRouteColor(i),
            strokeWeight: 6,
            extData: point
          });
        }
      } else {
        // 如果没有详细路线，则使用直线连接
        polylines.push({
          path: [previousPoint, customerLocation],
          strokeColor: getRouteColor(i),
          strokeWeight: 6,
          extData: point
        });
      }
      
      previousPoint = customerLocation;
    }
    
    setMapMarkers(markers);
    setMapPolylines(polylines);
  };

  // 获取不同路段的颜色
  const getRouteColor = (index: number): string => {
    const colors = ['#3366FF', '#33AA00', '#FF6600', '#CC33FF', '#FF3366', '#00CCFF'];
    return colors[index % colors.length];
  };

  // 格式化距离
  const formatDistance = (meters: number): string => {
    if (meters >= 1000) {
      return `${(meters / 1000).toFixed(1)}公里`;
    }
    return `${meters}米`;
  };

  // 格式化时间（分钟转换为小时+分钟）
  const formatDuration = (minutes: number): string => {
    const hours = Math.floor(minutes / 60);
    const mins = Math.round(minutes % 60);
    
    if (hours > 0) {
      return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`;
    }
    return `${mins}分钟`;
  };

  // 渲染交通方式图标
  const renderTransportIcon = (method: string) => {
    switch(method) {
      case 'driving':
        return <CarOutlined />;
      case 'walking':
        return <WalkIcon />;
      default:
        return <CarOutlined />;
    }
  };

  // 返回上一页
  const handleGoBack = () => {
    navigate(-1);
  };

  if (loading) {
    return <Spin tip="加载中..." style={{ width: '100%', marginTop: '100px' }} />;
  }

  if (!routePlan) {
    return (
      <div style={{ padding: '20px' }}>
        <Button icon={<ArrowLeftOutlined />} onClick={handleGoBack} style={{ marginBottom: '20px' }}>
          返回
        </Button>
        <Empty description="未找到路线计划数据" />
      </div>
    );
  }

  return (
    <div style={{ padding: '20px' }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={handleGoBack}>
            返回
          </Button>
          <Title level={2} style={{ margin: 0 }}>{routePlan.name}</Title>
        </Space>

        <div style={{ display: 'flex', gap: '20px' }}>
          {/* 左侧信息展示 */}
          <Card style={{ width: 300 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>日期：</Text>
                <Text>{routePlan.date}</Text>
              </div>
              <div>
                <Text strong>起点：</Text>
                <Text>{routePlan.startLocation.address}</Text>
              </div>
              <div>
                <Text strong>开始时间：</Text>
                <Text>{routePlan.startTime}</Text>
              </div>
              <div>
                <Text strong>结束时间：</Text>
                <Text>{routePlan.endTime}</Text>
              </div>
              <div>
                <Text strong>总距离：</Text>
                <Text>{formatDistance(routePlan.totalDistance)}</Text>
              </div>
              <div>
                <Text strong>总时间：</Text>
                <Text>{formatDuration(routePlan.totalDuration)}</Text>
              </div>
              <div>
                <Text strong>客户数量：</Text>
                <Text>{routePlan.points.length}</Text>
              </div>
              <div>
                <Text strong>交通方式：</Text>
                <Tag color="blue">{routePlan.points[0]?.travelMethod || 'N/A'}</Tag>
              </div>
            </Space>
          </Card>

          {/* 右侧地图和路线展示 */}
          <div style={{ flex: 1 }}>
            <MapComponent 
              center={mapCenter}
              markers={mapMarkers}
              polylines={mapPolylines}
              style={{ height: '400px', marginBottom: '20px' }}
            />

            <Card title="拜访路线详情">
              <Steps 
                direction="vertical" 
                current={routePlan.points.length}
              >
                <Step 
                  title="出发点" 
                  description={routePlan.startLocation.address}
                  icon={<EnvironmentOutlined />}
                />
                
                {routePlan.points.map((point, index) => (
                  <Step
                    key={index}
                    title={point.customer.name}
                    description={
                      <Space direction="vertical">
                        <Text>{point.customer.address}</Text>
                        <Space>
                          <ClockCircleOutlined />
                          <Text>到达：{point.arrivalTime}</Text>
                          <Text>离开：{point.departureTime}</Text>
                        </Space>
                        <Space>
                          {renderTransportIcon(point.travelMethod)}
                          <Text>距离：{formatDistance(point.travelDistance)}</Text>
                          <Text>用时：{formatDuration(point.travelTime)}</Text>
                        </Space>
                      </Space>
                    }
                    icon={<EnvironmentOutlined style={{ color: getRouteColor(index) }} />}
                  />
                ))}
              </Steps>
            </Card>

            <Divider />

            <Collapse>
              <Panel header="详细公交/驾车路线指引" key="1">
                <List
                  itemLayout="vertical"
                  dataSource={routePlan.points}
                  renderItem={(point, index) => {
                    const transitDetails = point.routeDetails?.route?.transits?.[0];
                    const drivingDetails = point.routeDetails?.route?.paths?.[0];
                    const walkingDetails = point.travelMethod === 'walking' ? point.routeDetails?.route?.paths?.[0] : null;
                    
                    if (point.travelMethod === 'transit' && transitDetails) {
                      return (
                        <List.Item>
                          <List.Item.Meta
                            title={`从 ${index === 0 ? '起点' : routePlan.points[index - 1].customer.name} 到 ${point.customer.name}`}
                          />
                          
                          {transitDetails.segments.map((segment: any, segIdx: number) => {
                            if (segment.walking && segment.walking.steps && segment.walking.steps.length > 0) {
                              return (
                                <div key={`walk-${segIdx}`} style={{ marginBottom: '8px' }}>
                                  <Space>
                                    <WalkIcon />
                                    <Tag color="green">步行</Tag>
                                    <Text>{formatDistance(segment.walking.distance)}</Text>
                                    <Text type="secondary">大约 {formatDuration(segment.walking.duration / 60)}</Text>
                                  </Space>
                                  <div style={{ marginLeft: '24px', color: '#666' }}>
                                    {segment.walking.steps.map((step: any, stepIdx: number) => (
                                      <div key={`walk-step-${stepIdx}`}>{step.instruction}</div>
                                    ))}
                                  </div>
                                </div>
                              );
                            } else if (segment.bus && segment.bus.buslines && segment.bus.buslines.length > 0) {
                              const busline = segment.bus.buslines[0];
                              return (
                                <div key={`bus-${segIdx}`} style={{ marginBottom: '8px' }}>
                                  <Space>
                                    <CarOutlined />
                                    <Text strong>{busline.name}</Text>
                                    <Text>从 {busline.departure_stop.name} 到 {busline.arrival_stop.name}</Text>
                                    <Text type="secondary">共 {busline.via_num + 1} 站</Text>
                                  </Space>
                                  <div style={{ marginLeft: '24px', color: '#666' }}>
                                    <div>上车站: {busline.departure_stop.name}</div>
                                    <div>下车站: {busline.arrival_stop.name}</div>
                                    <div>首班车: {busline.start_time}</div>
                                    <div>末班车: {busline.end_time}</div>
                                  </div>
                                </div>
                              );
                            }
                            return null;
                          })}
                        </List.Item>
                      );
                    } else if (point.travelMethod === 'walking' && walkingDetails) {
                      return (
                        <List.Item>
                          <List.Item.Meta
                            title={
                              <Space>
                                <span>{`从 ${index === 0 ? '起点' : routePlan.points[index - 1].customer.name} 到 ${point.customer.name}`}</span>
                                <Tag color="green" icon={<WalkIcon />}>步行路线</Tag>
                              </Space>
                            }
                          />
                          
                          {walkingDetails.steps?.map((step: any, stepIdx: number) => (
                            <div key={`step-${stepIdx}`} style={{ marginBottom: '8px' }}>
                              <Space>
                                <WalkIcon />
                                <Text>{step.instruction}</Text>
                                <Text type="secondary">{formatDistance(step.distance)}</Text>
                              </Space>
                            </div>
                          ))}
                        </List.Item>
                      );
                    } else if (point.travelMethod === 'driving' && drivingDetails) {
                      return (
                        <List.Item>
                          <List.Item.Meta
                            title={
                              <Space>
                                <span>{`从 ${index === 0 ? '起点' : routePlan.points[index - 1].customer.name} 到 ${point.customer.name}`}</span>
                                <Tag color="blue" icon={<CarOutlined />}>驾车路线</Tag>
                              </Space>
                            }
                          />
                          
                          {drivingDetails.steps?.map((step: any, stepIdx: number) => (
                            <div key={`step-${stepIdx}`} style={{ marginBottom: '8px' }}>
                              <Space>
                                <CarOutlined />
                                <Text>{step.instruction}</Text>
                                <Text type="secondary">{formatDistance(step.distance)}</Text>
                              </Space>
                            </div>
                          ))}
                        </List.Item>
                      );
                    }
                    
                    return (
                      <List.Item>
                        <Text>从 {index === 0 ? '起点' : routePlan.points[index - 1].customer.name} 到 {point.customer.name} 的路线信息不可用</Text>
                      </List.Item>
                    );
                  }}
                />
              </Panel>
            </Collapse>
          </div>
        </div>
      </Space>
    </div>
  );
};

export default RouteDetail;